package com.jxc.summer.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jxc.summer.dao.OutOrderMapper;
import com.jxc.summer.dao.StorageMapper;
import com.jxc.summer.exception.StorageNumException;
import com.jxc.summer.service.OutOrderService;
import com.jxc.summer.util.UUIDUtil;

@Service
@Transactional
public class OutOrderServiceImpl implements OutOrderService {

	@Autowired
	private OutOrderMapper outOrderMapper;
	@Autowired
	private StorageMapper storageMapper;
	
	@Override
	public boolean addout(Map<String, Object> params) {
		params.put("to_inorout", 2);
		int result = outOrderMapper.addOrderOut(params);
		if(result<1){
			throw new RuntimeException();
		}
		List<Map<String,Object>> orderList = (List<Map<String, Object>>) params.get("orderList");
		for (Map<String, Object> map : orderList) {
			map.put("toi_companycode", params.get("to_companycode"));
			map.put("toi_orderitemid", UUIDUtil.get32UUID());
			//添加订单条目
			result = outOrderMapper.addOrderOutItem(map);
			if(result<1){
				throw new RuntimeException();
			}
			//出库 更新库存即可，先查询再相减，如果大于0更新，等于0删除。
			//通过id获取库存数量
			Map<String,Object> getNumber = storageMapper.getStorageByid(map);
			float storageNum = MapUtils.getFloatValue(getNumber, "ts_number", 0);
			if(!(storageNum>0&&storageNum - MapUtils.getFloatValue(map, "toi_number")>=0)){
				throw new StorageNumException("库存不足！");
			}else{
				Map<String,Object> upm = new HashMap<String, Object>();
				upm.put("ts_storageid", MapUtils.getString(map, "ts_storageid"));
				upm.put("ts_number", storageNum - MapUtils.getFloatValue(map, "toi_number"));
				storageMapper.update(upm);
			}
			
		}
		return true;
	}

	@Override
	public Map<String, Object> pageList(Map<String, Object> params) {
		List<Map<String, Object>> list = outOrderMapper.pageList(params);
		int count = outOrderMapper.pageListCount(params);
		// package result
		Map<String, Object> maps = new HashMap<String, Object>();
		maps.put("recordsTotal", count);		// 总记录数
		maps.put("recordsFiltered", count);	// 过滤后的总记录数
		maps.put("data", list); 
		return maps;
	}

	@Override
	public Map<String, Object> getOrderByid(Map<String, Object> params) {
		return outOrderMapper.getOrderByid(params);
	}

	@Override
	public List<Map<String, Object>> getItemByOrderid(Map<String, Object> params) {
		return outOrderMapper.getItemByOrderid(params);
	}

}
